package cn.itcast.hotel.listener;

import cn.itcast.hotel.constants.EsConstants;
import cn.itcast.hotel.constants.MQConstans;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * mq监听类
 *
 * @Name : RabbitListenerConfiguration
 * @Author : WuQiang
 * @Date : 2022-09-22 16:28
 * @Description : mq监听类
 */
@Configuration
public class RabbitListenerConfiguration {

    @Autowired
    private IHotelService hotelService;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 插入或更新文档
     *
     * @param id id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MQConstans.HOTEL_INSERT_QUEUE),
            exchange = @Exchange(MQConstans.HOTEL_EXCHANGE_DIRECT),
            key = MQConstans.HOTEL_INSERT_KEY
    ))
    public void insertOrUpdateDocument(String id){
        try {
            //从数据库查询数据
            Hotel hotel = hotelService.getById(id);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            //创建请求  索引名称 文档id
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            //设置文档数据
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            //增加文档
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }


    /**
     * 删除文档
     *
     * @param id id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MQConstans.HOTEL_DELETE_QUEUE),
            exchange = @Exchange(value = MQConstans.HOTEL_EXCHANGE_DIRECT),
            key = MQConstans.HOTEL_DELETE_KEY
    ))
    public void deleteDocument(String id){
        try {
            DeleteRequest request = new DeleteRequest(EsConstants.HOTEL, id);
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }
}
